package lev01_beginnerClass.class06_binarySortFind;

import lev01_beginnerClass.util.HelpUtil;

import java.util.Arrays;

/**
 * binary search to find most right postion less than tagert num in ordered arrsy
 */
public class L03_FindRightMostTargetInOrderArray {
    public static void main(String[] args) {
        int maxTestTime = 3000;
        int maxLen = 20;
        int maxValue = 200;
        boolean succeed = true;
        for(int i = 0; i < maxTestTime;i++){
            int[] arr = HelpUtil.generateRandomArr(maxLen, maxValue);
            Arrays.sort(arr);
            int targetNum = (int)(Math.random()*(maxLen+1));
            if(forTest(arr,targetNum) != findMostRightLessThanTarget(arr,targetNum)){
                succeed = false;
                System.out.println(targetNum);
                System.out.println(Arrays.toString(arr));
                System.out.println(forTest(arr,targetNum));
                System.out.println(findMostRightLessThanTarget(arr,targetNum));
                break;
            }
        }
        System.out.println(succeed? "nice":"fuck");
    }

    /**
     * binary search to find most right postion less than tagert num in ordered arrsy
     *
     * @param arr    ordered arr
     * @param target target num
     * @return
     */
    public static int findMostRightLessThanTarget(int[] arr, int target) {
        //give priority to boundary conditon
        if(arr == null || arr.length == 0 ){
            return -1;
        }
        int left = 0;int right = arr.length-1;
        int ans = -1;
        while(left <= right){
            int mid = left + ((right - left) >> 1);
            if(arr[mid] <= target){
                ans = mid;
                left = mid+1;
            }else {
                right = mid -1;
            }
        }
        return ans;
    }

    /**
     * test method
     * @param arr ordered array
     * @param target target num
     * @return
     */

    public static int forTest(int[] arr,int target){
        if(arr == null || arr.length == 0){
            return  -1;
        }
        for(int i = arr.length-1; i>=0;i--){
            if(arr[i] <= target){
                return i;
            }
        }
        return -1;
    }
}


